<?php
namespace app\admin\controller;

use app\common\controller\SysAction;
use app\common\model\AuthGroup;
use app\common\model\UserInfo;
use app\common\model\AuthGroupAccess;
use think\Db;

class User extends SysAction
{
    protected $modelClass = '\app\common\model\User';
    protected $beforeActionList = [
        'noAction'  =>  ['only' => 'delete'],
    ];
    
    public function initialize()
    {
        parent::initialize();
    }
    
    public function index()
    {
        $where = [];
        if (input('get.search')){
            $where[] = ['username|name|email|mobile', 'like', '%'.input('get.search').'%'];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        $agMolde = new AuthGroup();
        $agList = $agMolde->select();
        $agListArr = [];
        $agListArrPic = [];
        foreach ($agList as $k => $v){
            $agListArr[$v['id']] = $v['title'];
            $agListArrPic[$v['id']] = $v['pic'];
        }
        foreach ($dataList as $k => $v){
            foreach ($v->userGroup as $k2 => $v2){
                $v['userGroup'][$k2]['title'] = $agListArr[$v2['group_id']];
                $v['userGroup'][$k2]['pic'] = $agListArrPic[$v2['group_id']];
            }
        }
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    
    public function create()
    {
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.add');
                if(true !== $result){
                    return ajax_return($result);
                }
                if ($data['address']) {
                    $location = $this->getAddress($data['address']);
                    $data['lng'] = $location['lng'];
                    $data['lat'] = $location['lat'];
                }
                $result = $this->cModel->allowField(true)->save($data);
                $uiModel = new UserInfo();
                $infoData = ['uid' => $this->cModel->id];
                $result2 = $uiModel->allowField(true)->save($infoData);
                // 提交事务
                if ($result && $result2){
                    Db::commit();
                    return ajax_return(lang('action_success'), url('index'));
                }else{
                    return ajax_return($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return($e->getMessage());
            }
        }else{
            return $this->fetch('create');
        }
    }
    
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if ($data['actions'] == 'password'){    //修改密码
                if ( $data['id'] != UID ){          //修改他人密码需验证旧密码
                    $oldData = $this->cModel->where(['id' => $data['id'], 'password' => md5($data['oldpassword'])])->find();
                    if (empty($oldData)){
                        ajax_return(lang('oldpassword_val'));
                    }
                }
                $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.password');
                if(true !== $result){
                    return ajax_return($result);
                }
                $result = $this->cModel->allowField(true)->save($data, $data['id']);
            }elseif ($data['actions'] == 'infos'){   //修改附加信息
                $uiModel = new UserInfo();
                if ( isset($data['birthday']) ){
                    $data['birthday'] = strtotime($data['birthday']);
                }
                $result = $uiModel->allowField(true)->save($data, ['uid' => $data['id']]);
                if ($result){
                    return ajax_return(lang('action_success'), url('index'));
                }else{
                    return ajax_return($uiModel->getError());
                }
            }else{   //修改信息
                if (count($data) == 2){
                    foreach ($data as $k =>$v){
                        $fv = $k!='id' ? $k : '';
                    }
                    $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.'.$fv);
                    if(true !== $result){
                        return ajax_return($result);
                    }
                    $result = $this->cModel->allowField(true)->save($data, $data['id']);
                }else{
                    if ($data['address']) {
                        $location = $this->getAddress($data['address']);
                        $data['lng'] = $location['lng'];
                        $data['lat'] = $location['lat'];
                    }
                    $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.edit');
                    if(true !== $result){
                        return ajax_return($result);
                    }
                    $result = $this->cModel->allowField(true)->save($data, $data['id']);
                }
            }
            if ($result){
                return ajax_return(lang('action_success'), url('index'));
            }else{
                return ajax_return($this->cModel->getError());
            }
        }else{
            $data = $this->cModel->get($id);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    private function getAddress($address=""){
        $key = confv('key');
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?key=".$key."&address=".$address;
        $result = httpRequest($url);
        $result = json_decode($result,1);
        if ($result['status'] == 0) {
            $location = $result['result']['location'];
        }
        return $location;
    }
    
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                Db::startTrans();
                try{
                    $id_arr = explode(',', $id);                        //用户数据
                    $where1[] = ['uid', 'in', $id_arr];
                    $where2[] = ['id', 'in', $id_arr];
                    
                    $uiModel = new UserInfo();
                    $data = $uiModel->where($where1)->select();         //查询用户附加表信息【用于删除头像】
                    
                    $result = $this->cModel->where($where2)->delete();  //删除主表数据
                    $result2 = $uiModel->where($where1)->delete();      //删除用户附加表
                    
                    $agaModel = new AuthGroupAccess();
                    $agaModel->where($where1)->delete();                //删除用户分配角色
                    // 提交事务
                    if ($result && $result2){
                        Db::commit();
                        foreach ($data as $k => $v){
                            if ($v['avatar'] != config('default_avatar')){
                                unlink(WEB_PATH.$v['avatar']);          //删除头像文件
                            }
                        }
                        return ajax_return(lang('action_success'), url('index'));
                    }else{
                        return ajax_return($this->cModel->getError());
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajax_return($e->getMessage());
                }
            }
        }
    }
    
    public function authGroup($id)
    {
        $agaModel = new AuthGroupAccess;
        if (request()->isPost()){
            $data = input('post.');
            $uid = $data['id'];
            $group_id = $data['group_id'];
            $where = ['uid' => $uid];
            $agaModel->where($where)->delete();
            if (!empty($group_id)){
                $addList = array();
                foreach ($group_id as $k =>$v){
                    $addList[] = ['uid' => $uid, 'group_id' => $v];
                }
                $agaModel->saveAll($addList, false);
            }
            return ajax_return(lang('action_success'), url('index'));
        }else{
            $agModel = new AuthGroup();
            $groupList = $agModel->where(['status' => 1])->order('module ASC,level ASC,id ASC')->select();      //所有正常角色
            $userGroup = $agaModel->where(['uid' => $id])->select();                                            //当前用户已拥有角色
            foreach ($groupList as $k => $v){
                foreach ($userGroup as $k2 => $v2){
                    if ($v2['group_id'] == $v['id']){
                        $groupList[$k]['ischeck'] = 'y';
                        break;
                    }
                }
            }
            $data = $this->cModel->get($id);
            $this->assign('data', $data);
            $this->assign('groupList', $groupList);
            return $this->fetch();
        }
    }
    
    protected function noAction()
    {
        if (request()->isPost()){
            $config_admin = config('app.AUTH_CONFIG.AUTH_ADMIN');
            $id = input('param.id');
            $id_arr = explode(',', $id);
            foreach ($config_admin as $k => $v){
                if(in_array($v, $id_arr)){
                    return ajax_return(lang('not_edit'));
                    exit();
                }
            }
        }
    }
}